<template>
  <div class="overview_site">
    <div class="page-title">{{$t('device.inverter.siteName')}}:<span>{{siteName}}</span></div>
    <div class="flex-container">
      <div class="flex-item sun-box">
        <div class="sun-wrap clearfix">
						<div class="sun-box-pix">
							<div class="sun-gif">
								<img src="../../assets/img/sun/sun-bg.png" width="100%">
								<img src="../../assets/img/sun/sun-big.png" width="100%" class="sun-rotate" :style="'transform:rotate('+sunData.sunAngle+'deg)'" v-show="isSunFlag">
							</div>
						</div>
						<div class="sun-time-day"><span class="sun-up-time">{{sunData.startTime}}</span><span class="sun-down-time pull-right">{{sunData.endTime}}</span></div>
						<div class="weather-box col-xs-6">
              <img class="weather-pic-box" :title="isSunFlag?sunData.txtd:sunData.txtn" :src="sunData.weatherImg">
							<span class="weather-info-temperature" id="temperature-name">{{sunData.tmpMin?sunData.tmpMin+' ~ '+sunData.tmpMax+'℃':''}}</span>
						</div>
						<div class="powerData inner col-xs-6">
							<div class="wrap">
								<label>{{$t('index.powerNow')}}:</label>
                <span class="value">{{gridPower | numberFloatFrm(false) | getByIndex(0)}}</span>
                <span class="unit">{{gridPower | numberFloatFrm(false) | getByIndex(1)}}</span>
							</div>
							<div class="wrap" data-toggle="modal" data-target="#mapModal">
								<img v-if="sunData.cnty" src="../../assets/img/map/marker.png" alt="map" class="map-marker" @click="showMap()"/>
								<span >{{sunData.cnty}}</span>
							</div>
						</div>
					</div>
      </div>
      <div class="flex-item box-power">
          <div class="row">
            <div class="col">
              <div class="wrap">
                <div class="img icon1"></div>
                <div class="text">
                  <span class="value">{{yieldObj.todayYield | numberFloatFrm(true) | getByIndex(0)}}</span>
                  <span class="unit">{{yieldObj.todayYield | numberFloatFrm(true) | getByIndex(1)}}</span>
                  <p>{{$t('overview.daily_generateElectricity')}}</p>
                </div>
              </div>
            </div>
            <div class="col">
              <div class="wrap">
                <div class="img icon2"></div>
                <div class="text">
                  <span class="value">{{yieldObj.monthYield | numberFloatFrm(true) | getByIndex(0)}}</span>
                  <span class="unit">{{yieldObj.monthYield | numberFloatFrm(true) | getByIndex(1)}}</span>
                  <p>{{$t('overview.month_generateElectricity')}}</p>
                </div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="wrap">
                <div class="img icon3"></div>
                <div class="text">
                  <span class="value">{{yieldObj.yearYield | numberFloatFrm(true) | getByIndex(0)}}</span>
                  <span class="unit">{{yieldObj.yearYield | numberFloatFrm(true) | getByIndex(1)}}</span>
                  <p>{{$t('overview.year_generateElectricity')}}</p>
                </div>
              </div>
            </div>
            <div class="col">
              <div class="wrap">
                <div class="img icon4"></div>
                <div class="text">
                  <span class="value">{{yieldObj.totalYield | numberFloatFrm(true) | getByIndex(0)}}</span>
                  <span class="unit">{{yieldObj.totalYield | numberFloatFrm(true) | getByIndex(1)}}</span>
                  <p>{{$t('overview.total_generateElectricity')}}</p>
                </div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="wrap">
                <div class="img icon3"></div>
                <div class="text">
                  <span class="unit">{{electricity.currency}}</span>
                  <span class="value">{{electricity.price | floatNum}}</span>
                  <p>
                    {{$t('overview.savingElectricity')}}
                    <el-tooltip :content="$t('site.ElectricPrice')">
                      <i class="iconfont icon-tag color_text pointer hover" @click="()=>{$store.commit('setVisibleShow',true)}"></i>
                    </el-tooltip>
                  </p>
                </div>
              </div>
            </div>
            <div class="col">
              <div class="wrap">
                <div class="img icon4"></div>
                <div class="text">
                  <span class="value">{{yieldObj.totalYield | convertUnit('weight') | getByIndex(0)}}</span>
                  <span class="unit">{{yieldObj.totalYield | convertUnit('weight') | getByIndex(1)}}</span>
                  <p>{{$t('overview.CO2Reduction')}}</p>
                </div>
              </div>
            </div>
          </div>
      </div>
      
      <div class="flex-item box-info">
        <ul class="list">
          <li class="title">{{$t('overview.Information_Statistics')}}</li>
          <li>
            <span class="img"><img src="../../assets/img/overview/stats-inv.png"></span>
            <span class="name">{{$t('overview.total_inverter')}}: {{siteInfo.total}}</span>
            <span class="value"></span>
          </li>
          <li>
            <span class="img"><img src="../../assets/img/overview/stats-invOnline.png"></span>
            <span class="name">{{$t('overview.online_inverter')}}: {{siteInfo.active}}</span>
            <span class="value"></span>
          </li>
        </ul>
      </div>
    </div>
    <div class="flex-container">
      <div class="flex-item box-sale-bar">
        <div class="title">
          {{$t('overview.gridPower')}}
          <span class="time-group">
            <button :class="{disabled:powerChartDate==currentDate}" @click="setDateVal(-1)"><i class="el-icon-arrow-left el-icon--left"></i></button>
            <el-date-picker
              v-model="powerChartDate"
              type="date"
              value-format="yyyy-MM-dd"
              @change="initPowerChart()"
              :clearable='false'
              :picker-options="pickerOptions"
              size="mini">
            </el-date-picker>
            <button :disabled="powerChartDate==currentDate" @click="setDateVal(1)"><i class="el-icon-arrow-right el-icon--right"></i></button>
          </span>
          
        </div>
        <div id="powerChart" :style="{width: '100%', height: '300px'}"></div>
      </div>

      <div class="flex-item box-power-bar">
        <div class="title clearfix">
          <span>{{$t('index.totalConsumption')}}</span>
          <el-select v-model="yeildType" size="mini" v-show="chartType=='bar'" @change="initYieldChart(chartType,reportType)">
            <el-option value='1' :label="$t('overview.currentYield')"></el-option>
            <el-option value='2' :label="$t('overview.used')"></el-option>
          </el-select>
          <ul class="chartBtnWrap">
            <li :class="chartType=='pie'?'active':''" @click="initYieldChart('pie',reportType)"><i class="iconfont icon-chartPie"></i></li>
            <li :class="chartType=='bar'?'active':''" @click="initYieldChart('bar',reportType)"><i class="iconfont icon-chartBar"></i></li>
          </ul>
        </div>
        <div class="btn-group2 right-box-radio clearfix"> 
          <div class="radio-wrap">
            <div :class="reportType==1?'active':''" @click="initYieldChart(chartType,1)">
              <span class="radio-box-modal"></span><font>{{$t('overview.daily')}}</font>：
            </div>
            <div class="btn-group">
              <span class="box-title" :class="{ active:isActive==1 }" @click.stop="toggleBox(1)">
                <span class="title-btn" id="day_menu">{{day}}</span><i class="el-icon-caret-bottom"></i>
              </span>

              <ul class="box-time" style="width:210px">
                <li class="title">{{$t('overview.daily')}}</li>
                <template v-for="count in dayList" >
                  <li :key="count" @click="day=count;isActive=0">{{count}}</li>
                </template>
              </ul>
            </div>
          </div>

          <div class="radio-wrap">
            <div :class="reportType==2?'active':''" @click="initYieldChart(chartType,2)">
              <span class="radio-box-modal"></span><font>{{$t('overview.month')}}</font>：
            </div>
            <div class="btn-group">
              <span class="box-title" :class="{ active:isActive==2 }" @click.stop="toggleBox(2)">
                <span class="title-btn" id="month_menu">{{month}}</span><i class="el-icon-caret-bottom"></i>
              </span>
              <ul class="box-time" colspan="6">
                <li class="title">{{$t('overview.month')}}</li>
                <template v-for="count in 12" >
                  <li :key="count" @click="month=count;isActive=0">{{count}}</li>
                </template>
              </ul>
            </div>
          </div>

          <div class="radio-wrap">
            <div :class="reportType==3?'active':''" @click="initYieldChart(chartType,3)">
              <span class="radio-box-modal"></span><font>{{$t('overview.year')}}</font>：
            </div>
            <div class="btn-group">
              <span class="box-title" :class="{ active:isActive==3 }" @click.stop="toggleBox(3)">
                <span class="title-btn" id="year_menu">{{year}}</span><i class="el-icon-caret-bottom"></i>
              </span>
              <ul class="box-time">
                <li class="title">{{$t('overview.year')}}</li>
                <template v-for="count in yearList">
                  <li class="grow" :key="count" @click="year=count;isActive=0">{{count}}</li>
                </template>
              </ul>
            </div>
          </div>

          <div class="radio-wrap">
            <div :class="reportType==4?'active':''" @click="initYieldChart(chartType,4)"> 
              <span class="radio-box-modal"></span>{{$t('all')}}
            </div>
          </div>
        </div>
        <div class="wrap-chart">
          <div class="wrap-pie" :class="{active:chartType=='pie'}">
            <div echart id="yieldPieChart1">1</div>
            <div echart id="yieldPieChart2">2</div>
            <div class="info">{{$t('overview.currentYield')}}:<span class="value">{{pieYield}}</span></div>
            <div class="info">{{$t('overview.used')}}:<span class="value">{{pieConsumeEnergy}}</span></div>
          </div>
          <div class="wrap-bar" :class="{active:chartType=='bar'}">
            <div echart id="yieldBarChart" :style="{width: '100%', height: '300px'}"></div>
          </div>
        </div>
      </div>
    </div>
    <el-tooltip class="prompt" effect="dark" :content="$t('overview.importantNode')" placement="right">
      <i class="el-icon-warning"></i>
    </el-tooltip>
    <setPriceModal :siteId="siteId" @uploadPage="saveElectricity"></setPriceModal>
    <baseBaiduMap :markers='markers' :mapData='mapData'></baseBaiduMap>
    <baseGoogleMap :markers='markers' :mapData='mapData'></baseGoogleMap>
  </div>
</template>

<script>
import '@/utils/index.js'
import baseBaiduMap from '../../components/map/baseBaiduMap'
import baseGoogleMap from '../../components/map/baseGoogleMap'
import setPriceModal from '../site/set_price'
let echarts = require('echarts/lib/echarts');
require('echarts/lib/chart/pie')

export default {
  components:{
    baseBaiduMap,
    baseGoogleMap,
    setPriceModal
  },
  data(){
    return{
      markers:[],
      mapData:{
          width:'100%',
          height:'400px',
          zoom:10,
          center:{
              lng:113,
              lat:29
          },
          mapObj:{},//地图对象
          markers:[],//地图上所有的标记
      },
      siteId:'',
      siteName:'',
      userData:JSON.parse(sessionStorage.getItem('userObj')),
      isSunFlag:true,
      sunData:{startTime:'6:00AM',endTime:'6:00PM',sunAngle:0,weatherImg:''},
      gridPower:0,
      yieldObj:{todayYield:0,monthYield:0,yearYield:0,totalYield:0},
      electricity:{price:'',currency:''},//节约电费
      userPower:{},
      siteInfo:{},
      powerChartDate:this.$options.filters['dateFormat'](new Date(),'YYYY-MM-DD'),
      chartType:'pie',
      reportType:'1',
      yeildType:'1',
      pieYield:0,
      pieConsumeEnergy:0,
      currentTime:this.$options.filters['dateFormat'](new Date()),
      currentDate:this.$options.filters['dateFormat'](new Date(),'YYYY-MM-DD'),
      day:this.$options.filters['dateFormat'](new Date(),'DD'),
      month:this.$options.filters['dateFormat'](new Date(),'MM'),
      year:this.$options.filters['dateFormat'](new Date(),'YYYY'),
      yearList:[],
      isActive:0,
      powerChart:{},
      yieldPieChart1:{},
      yieldPieChart2:{},
      yieldBarChart:{},
      pickerOptions:{ //禁用今天之后的时间
          disabledDate(time) {
              return time.getTime() > Date.now()
          }
      }
    }
  },
  mounted(){
    this.siteId=this.$route.query.siteId
    this.siteName=this.$route.query.siteName
    for(let i=2018;i<=this.year;i++){
      this.yearList.push(i);
    }
    this.getYeildyBySite();//获取当前发电量
    this.getPowerBySite();//获取当前功率
    this.getSiteInfoCount();//获取信息统计
    this.getSunBySite();//获取太阳动画数据
    // this.saveElectricity();//节约电费
    this.powerChart = echarts.init(document.getElementById('powerChart'));
    this.yieldPieChart1 = echarts.init(document.getElementById('yieldPieChart1'));
    this.yieldPieChart2 = echarts.init(document.getElementById('yieldPieChart2'));
    this.yieldBarChart = echarts.init(document.getElementById('yieldBarChart'));
    this.initPowerChart();//功率曲线
    this.initYieldChart(this.chartType,this.reportType);
    window.addEventListener('resize', () => {
      this.powerChart.resize();
      this.yieldPieChart1.resize()
      this.yieldPieChart2.resize()
      this.yieldBarChart.resize()
    })
    document.addEventListener('click',this.toggleBox);
    this.getMap()
  },
  destroyed(){
    document.removeEventListener('click',this.toggleBox);
  },
  computed: {
    dayList: function () {
      if(this.month==1||this.month==3||this.month==5||this.month==7||this.month==8||this.month==10||this.month==12) return 31;
      if(this.month==4||this.month==6||this.month==9||this.month==11) return 30;
      if(this.month==2&&this.year%4==0) return 28;
      if(this.month==2&&this.year%4!=0) return 29;
    }
  },
  watch:{
    day(){
      this.initYieldChart(this.chartType,this.reportType);
    },
    month(){
      this.day=1;
      this.initYieldChart(this.chartType,this.reportType);
    },
    year(){
      this.day=1;
      this.initYieldChart(this.chartType,this.reportType);
    }
  },
  methods:{
    //切换时间
    setDateVal(append){
      this.powerChartDate=this.UtilsFun.setReportDate(this.powerChartDate,append);
      this.initPowerChart();
    },
    toggleBox(index){
      index=index!=0?index:0;
      if(index==0) console.log(index);
      if (this.isActive==index) {
        this.isActive=0;
      }else{
        this.isActive=index;
      }
    },
    forEachYield(res,i,xAxisData,yAxisData,g_data,d_data,c_data){
      let flag=true;
      res.forEach(item=>{
        if(item.time==i){
          xAxisData.push(item.time);
          if(item.yieldtoday!=null){
            if(item.yieldtoday<=0){
              yAxisData.push(0.00);
            }else{
              yAxisData.push(item.yieldtoday.toFixed(2));
            }
          }else{
            yAxisData.push('-');
          }
          
          if(item.feedinenergy!=null){
						if(item.feedinenergy<=0){
							g_data.push(0.00);
						}else if(item.yieldtoday>=0 && item.yieldtoday<item.feedinenergy){
							//处理并网电量大于发电量时   并网电量显示发电量
							g_data.push(item.yieldtoday.toFixed(2));
						}else{
							g_data.push(item.feedinenergy.toFixed(2));
						}
					}else{
						g_data.push('-');
          }
          
          if(item.yieldtoday!=null && item.feedinenergy!=null){
						if(item.yieldtoday-item.feedinenergy<=0){
							d_data.push(0.00);
						}else{
							d_data.push((item.yieldtoday-item.feedinenergy).toFixed(2));
						}
					}else{
						d_data.push('-');
          }
          
          if(item.consumeenergy!=null){
						if(item.consumeenergy<=0){
							c_data.push(0.00);
						}else{
							c_data.push(item.consumeenergy.toFixed(2));
						}
					}else{
						c_data.push('-');
					}
          flag=false;
        }
      })
      if (flag) {
				xAxisData.push(i);
				yAxisData.push('-');
				g_data.push('-');
				d_data.push('-');
				c_data.push('-');
			}
    },
    async getYeildyBySite(){
      let res=await this.API.getYeildyBySite({
        siteId:this.siteId,
        currentTime: this.currentTime
      })
      this.yieldObj=res;
    },
    //信息统计
    async getSiteInfoCount(){
      let res = await this.API.getSiteInfoCount({
        siteId: this.siteId
      })
      this.siteInfo=res;
    },
    //当前功率
    async getPowerBySite(){
      let res = await this.API.getPowerBySite({
        siteId:this.siteId,
        currentTime: this.currentTime
      })
      this.gridPower=res.gridPower;
    },
    //节约电费
    async saveElectricity(){
      let res = await this.API.saveElectricity({
        siteId:this.siteId
      })
      this.electricity=res;
    },
    //获取太阳动画数据
    async getSunBySite(){
      let res = await this.API.getSunBySite({
        id: this.siteId
      })

      var convertTime=function (time){
        var timeArr=time.split(':');
        if(parseInt(time)>=12){
          return timeArr[0]-12+':'+timeArr[1]+'PM';
        }else{
          return timeArr[0]-0+':'+timeArr[1]+'AM';
        }
      }
      if(res){
        this.sunData=Object.assign(this.sunData,res)
        res.sr=res.sr?res.sr:'06:00';
        res.ss=res.ss?res.ss:'18:00';
        this.sunData.startTime=convertTime(res.sr);
        this.sunData.endTime=convertTime(res.ss);
        if(!res.date){
          var date=new Date();
					res.date=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
        }
        var startTime=new Date(res.date.replace(/-/g,'/')+' '+res.sr+':00').getTime();//开始时间
        var endTime=new Date(res.date.replace(/-/g,'/')+' '+res.ss+':00').getTime();//结束时间
        var date = res.nowUtcTime?new Date(res.nowUtcTime):new Date();
        if(date>startTime && date<endTime){
          var hours=date.getHours();
          var minutes=date.getMinutes();
          var nowTime=date.getTime();//现在时间
          var startNormalAngle=new Date(date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate()+' 08:00:00').getTime();//当天8:00
          var endNormalAngle=new Date(date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate()+' 16:00:00').getTime();//当天16:00
          //日出日落
          var angle;
          if(nowTime<startNormalAngle){//现在时间小于8点
            angle=12/(startNormalAngle-startTime)*(nowTime-startTime)+8;
          }else if(nowTime>endNormalAngle){//现在时间大于晚上16点
            angle=158+12/(endTime-endNormalAngle)*(nowTime-endNormalAngle);
          }else{
            angle=(hours-6)*15-1;//旋转角度
            if(minutes>0){
              if(hours%2==0){
                angle+=9;
              }else{
                angle+=6;
              }
            }
          }
          this.sunData.sunAngle=angle;
          this.isSunFlag=true;
          this.sunData.weatherImg=this.sunData.coded?require('../../assets/img/weather/'+this.sunData.coded+'.png'):'';
        }else{
          this.isSunFlag=false;
          this.sunData.weatherImg=this.sunData.coden?require('../../assets/img/weather/'+this.sunData.coden+'.png'):'';
        }
      }
    },
    initYieldPie(chartObj,chartData){
      let option = {
          color:chartData.color,
            tooltip: {
                trigger: 'item',
                formatter: '{b} : {c}kWh'
            },
            legend: {
                left: 'center',
                bottom:5,
                icon: 'circle',
                itemGap:15,
                itemWidth:12,
                itemHeight:12,
                data: chartData.legend,
                textStyle: {
                    rich: {
                        value: {
                            fontSize: 12,
                            lineHeight: 12,
                            color: '#ff8920'
                        }
                    }
                }
            },
            series: [
                {
                    type: 'pie',
                    radius: ['30%', '50%'],
                    center: ['50%', '43%'],
                    hoverOffset:3,
                    label:{
                      normal: {
                        show: true,
                        formatter: (params)=>{
                                return params.percent+'%';
                            },
                        textStyle: {
                          fontSize: 15,
                        },
                        position: 'outside'
                      }
                    },
                    labelLine:{
                      show:false,
                      length:10,
                      length2:0
                    },
                    data: chartData.series,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
      chartObj.setOption(option, true);
    },
    //电量统计
    async initYieldChart(chartType,reportType){
      console.log(chartType);
      this.chartType=chartType;
      this.reportType=reportType;
      var dateTime='';
      let m = this.month>9?this.month:"0"+this.month;//获取当前月份的日期
      let d = this.day>9?this.day:"0"+this.day;
      if(this.reportType==1) dateTime=this.year+'-'+m+'-'+d
      if(this.reportType==2) dateTime=this.year+'-'+m
      if(this.reportType==3) dateTime=this.year


      if(this.chartType=='pie'){
        let data = await this.API.getAggYieldBySite({
          reportType : reportType,
          dateTime : dateTime,
          currentTime : this.currentDate,
          siteId: this.siteId
        })
        console.log(data);
        if(data){
          //yield发电量   feedinEnergy 并网电量    consumeEnergy耗电电量
          //自发自用=发电量-并网电量
          if(data.feedinEnergy > data.yield){
            data.feedinEnergy = data.yield
          }
          this.pieYield = data['yield']>1000?(data['yield']/1000).toFixed(2)+'MWh':data['yield'].toFixed(2)+'kWh'
          this.pieConsumeEnergy = data['consumeEnergy']>1000?(data['consumeEnergy']/1000).toFixed(2)+'MWh':data['consumeEnergy'].toFixed(2)+'kWh'
          var selfUser=data['yield']-data['feedinEnergy']>0?data['yield']-data['feedinEnergy']:0;
          var pieChartData={
              color:['#f4b600','#6da719'],
              legend:[this.$t('index.toGrid'),this.$t('index.directSelfUse')],
              series:[
                      {value: data['feedinEnergy'].toFixed(2), name: this.$t('index.toGrid')},
                      {value: selfUser.toFixed(2), name: this.$t('index.directSelfUse')},
                    ]
          };
          var pieChart2Data={
              color:['#eb6206','#6da719'],
              legend:[this.$t('index.powerConsumption'),this.$t('index.directSelfUse')],
              series:[
                      {value: data['consumeEnergy'].toFixed(2), name: this.$t('index.powerConsumption')},
                      {value: selfUser.toFixed(2), name: this.$t('index.directSelfUse')},
                    ]
          };
          this.initYieldPie(this.yieldPieChart1,pieChartData)
          this.initYieldPie(this.yieldPieChart2,pieChart2Data);
        }
      }else if(this.chartType='bar'){
        let res = await this.API.getYeildyChartBySite({
          reportType : reportType,
          day : this.day,
          month : this.month,
          year : this.year,
          webTime : this.$options.filters['dateFormat'](new Date(),'YYYY,MM,DD')
        })

        let resData=res.returnList;//数据
        let maxTick=res.max;//最大刻度

        let xAxisData=[],yAxisData=[],g_data=[],d_data=[],c_data=[];
        let array_data1=[],array_data2=[],array_data3=[],array_data4=[];
        let theMax1=0,theMax2=0,theMax3=0,theMax4=0;//最大值
        let _this=this;
        let unit_time='';

        if(resData!=null && resData.length>0){
          resData.forEach(item=>{
            array_data1.push(item.yieldtoday<0?0:item.yieldtoday);
            array_data2.push(item.feedinenergy<0?0:item.feedinenergy);
            if(item.yieldtoday!=null && item.feedinenergy!=null){
              array_data3.push(item.yieldtoday-item.feedinenergy<0?0:(item.yieldtoday-item.feedinenergy));
            }else{
              array_data3.push(null);
            }
            array_data4.push(item.consumeenergy<0?0:item.consumeenergy);//耗电量
          })
          theMax1=(this.$options.filters['MaxNum'](array_data1)/10000).toFixed(2);
          theMax2=(this.$options.filters['MaxNum'](array_data2)/10000).toFixed(2);
          theMax3=(this.$options.filters['MaxNum'](array_data3)/10000).toFixed(2);
          theMax4=(this.$options.filters['MaxNum'](array_data4)/10000).toFixed(2);//耗电量
        }
        
          //根据日期类型初始化数据
          if(reportType==1){
            unit_time=this.$t('index.unitTimeHour');
            let hour=23;
            for(let i=0;i<=hour;i++){
              this.forEachYield(resData,i,xAxisData,yAxisData,g_data,d_data,c_data);
            }
          }else if(reportType==2){
            unit_time=this.$t('index.unitTimeDay');
            for(let i=1;i<=this.dayList;i++){
              this.forEachYield(resData,i,xAxisData,yAxisData,g_data,d_data,c_data);
            }
          }else if(reportType==3){
            unit_time=this.$t('index.unitTimeMonth');
            for(let i=1;i<=12;i++){
              this.forEachYield(resData,i,xAxisData,yAxisData,g_data,d_data,c_data);
            }
          }else if(reportType==4){
            unit_time=this.$t('index.unitTimeYear');
            let temp;
            for(var i=0; i < resData.length; i++){
              for(var j=0; j < resData.length-i-1; j++){
                if(resData[j].time>resData[j+1].time){
                  temp=resData[j];
                  resData[j]=resData[j+1];
                  resData[j+1]=temp;
                }
              }             
            }

            resData.forEach(item=>{
              xAxisData.push(item.time);
              if(item.yieldtoday!=null){
                if(item.yieldtoday<=0){
                  yAxisData.push(0.00);
                }else{
                  yAxisData.push(item.yieldtoday.toFixed(2));
                }
              }else{
                yAxisData.push('-');
              }
              
              if(item.feedinenergy!=null){
                if(item.feedinenergy<=0){
                  g_data.push(0.00);
                }else if(item.yieldtoday>=0 && item.yieldtoday<item.feedinenergy){
                  //处理并网电量大于发电量时   并网电量显示发电量
                  g_data.push(item.yieldtoday.toFixed(2));
                }else{
                  g_data.push(item.feedinenergy.toFixed(2));
                }
              }else{
                g_data.push('-');
              }
              
              if(item.yieldtoday!=null && item.feedinenergy!=null){
                if(item.yieldtoday-item.feedinenergy<=0){
                  d_data.push(0.00);
                }else{
                  d_data.push((item.yieldtoday-item.feedinenergy).toFixed(2));
                }
              }else{
                d_data.push('-');
              }
              
              if(item.consumeenergy!=null){
                if(item.consumeenergy<=0){
                  c_data.push(0.00);
                }else{
                  c_data.push(item.consumeenergy.toFixed(2));
                }
              }else{
                c_data.push('-');
              }
            })
          }

          let yeildData;
          if(this.yeildType=='1'){
            yeildData={name:this.$t('index.toGrid'),color:'#f4b600',data:g_data}
          }else if(this.yeildType=='2'){
            yeildData={name:this.$t('index.powerConsumption'),color:'#eb6206',data:c_data}
          }

          let optionObj={
            tooltip:{
              formatter: function (params) {
                if(params.length==0) return ""
                var text = _this.$options.filters['formatUnitTime'](unit_time,params[0]['axisValue'])+'<br>';
                if(params.length>0){
                  var params1=params[0]['data']=='-'?'-':parseFloat(params[0].data).toFixed(2);
                  text += params[0]['seriesName']+' : '+params1+'kWh<br>';
                }
                if(params.length>1){
                  var params2=params[1]['data']=='-'?'-':parseFloat(params[1].data).toFixed(2);
                  text += params[1]['seriesName']+' : '+params2+'kWh<br>';
                }
                if(params.length>2){
                  var params3=params[2]['data']=='-'?'-':parseFloat(params[2].data).toFixed(2);
                  text += params[2]['seriesName']+' : '+params3+'kWh<br>';
                }
                return text;
              }
            },
            legend:{
              data:[{name : yeildData.name,icon : 'stack'},{name : this.$t('index.directSelfUse'),icon : 'stack'}]
            },
            xAxis:{
              name:'('+unit_time+')',
              data : xAxisData
            },
            yAxis:{
              name:'kWh'
            },
            grid : {
              left : '15px',
              top : '50px',
              right : '70px',
              bottom : '40px',
              containLabel :true
            },
            series : [
              this.EchartsUtil.getSeries({type:'bar',name:yeildData.name,barMaxWidth:20,stack:'one',color:yeildData.color,data:yeildData.data}),
              this.EchartsUtil.getSeries({type:'bar',name:this.$t('index.directSelfUse'),barMaxWidth:20,stack:'one',color:'#6DA719',data:d_data}),
            ]
          };
          this.yieldBarChart.setOption(this.EchartsUtil.getOption(optionObj));
        }

    },
    //功率曲线
    async initPowerChart(){
      let res = await this.API.getSitePowerBySite({
        siteId:this.siteId,
        time: this.powerChartDate
      })
      //判断是否有其他设备功率
      let flag_other=false
      res.forEach(item=>{
        if(item.feedinPowerMeter2){
          flag_other=true
        }
      })
      let siteAndOverOther=this.$t('overview.siteAndOver.other');
      let selectedArray=[this.$t('index.solarPower'),this.$t('index.outPutPower'),this.$t('newoverView.relayPower'),this.$t('index.feedInPower')];
      let colorArray=['#f4b600','#72BC38','#C962F7','#eb6206'];
      if(flag_other){
        selectedArray.unshift(this.$t('overview.siteAndOver.other'));
        colorArray.unshift('#0DDEB2');
      }

      // let powerdc=0;//PV功率
      // let gridpower;//AC功率
      // let feedinpower;//并网功率
      // let batPower;//电池功率
      // let overOther//其他设备功率
      // let loadPower;//负载功率

      let times1=[],times2=[],times3=[],times4=[],times5=[],times6=[];
      res.forEach(item=>{
        let powerdc=0;
        if(item.powerdc1){
          powerdc += item.powerdc1;
        }
        if(item.powerdc2){
          powerdc += item.powerdc2;
        }
        if(item.powerdc3){
          powerdc += item.powerdc3;
        }
        if(item.powerdc4){
          powerdc += item.powerdc4;
        }
        let time=new Date(Date.parse( (item.uploadTimeValue.replace(/-/g,"/")).replace(/\./g,"") )).getTime()
        times1.push([time,powerdc]);//pv功率
        times2.push([time,item.gridpower]);//AC功率
        times3.push([time,item.relayPower||0]);//负载
        times4.push([time,item.feedinpower]);//并网功率
        // times6.push([time,item.feedinPowerMeter2]);//其它功率
        // times5.push([time,item.batPower1]);//电池功率
      })

      var option = {
          color:colorArray,
          tooltip: {
              trigger: 'axis',
          },
          legend: {
            show : true,
            itemGap : 30,// 间距
            y : 'bottom',
            data: [this.$t('index.solarPower'),this.$t('index.outPutPower'),this.$t('newoverView.relayPower'),this.$t('index.feedInPower')],
            textStyle : {
              color : '#68676C',
              fontSize : 12
            }
          },
          grid : {
            left : '15px',
            top : '50px',
            right : '40px',
            bottom : '40px',
            containLabel :true
          },
          xAxis: {
              type: 'time',
              nameTextStyle:{
                color : '#68676C',
                fontSize:11
              },
              axisLine: {
                onZero: false,
                lineStyle:{
                  width:0
                }
              },
              axisTick : {
                inside : false
              },
              splitLine: {
                  show: false
              },
              axisLabel : {
                formatter: function(value,index){
                  var date = new Date(value);
                  var hour = date.getHours()<10?'0'+ date.getHours():date.getHours();
                  var minutes = date.getMinutes()<10?'0'+ date.getMinutes():date.getMinutes();
                  return hour+':'+minutes;
                },
                textStyle : {
                  color : '#68676C'
                }
              }
          },
          yAxis: {
              type: 'value',
              nameTextStyle: {
                color: '#777',
                fontSize: 12,
              },
              axisLine : {
                show : false
              },
              axisTick : {
                show : false
              },
              splitLine : {
                show : true,
                lineStyle : {
                  color : [ '#dbdbdc' ]
                }
              },
              axisLabel : {
                formatter: '{value} W',
                textStyle : {
                  color : '#68676C'
                }
              }
          },
          series: [{
              name: this.$t('index.solarPower'),
              type: 'line',
              symbol: 'none',
              smooth : true,
              lineStyle:{
                width:1
              },
              areaStyle: {
                opacity:0.3
              },
              data:times1
          },{
              name: this.$t('index.outPutPower'),
              type: 'line',
              symbol: 'none',
              smooth : true,
              lineStyle:{
                width:1
              },
              areaStyle: {
                opacity:0.3
              },
              data:times2
          },{
              name: this.$t('newoverView.relayPower'),
              type: 'line',
              symbol: 'none',
              smooth : true,
              smooth : true,
              lineStyle:{
                width:1
              },
              areaStyle: {
                opacity:0.3
              },
              data:times3
          },{
              name: this.$t('index.feedInPower'),
              type: 'line',
              symbol: 'none',
              smooth : true,
              smooth : true,
              lineStyle:{
                width:1
              },
              areaStyle: {
                opacity:0.3
              },
              data:times4
          }]
      };
      this.powerChart.setOption(option);
    },
    async getMap(){
      let res = await this.API.selectSiteMapAddress({
        id:this.siteId
      })
      console.log(res,'----------------------res  point')
      if(res.longitude!=''&&res.longitude!=null&&res.latitude!=''&&res.latitude!=null){
          let pointType=localStorage.getItem('mapType')==1?'baidu':'google'
          var transParam = this.UtilsFun.transformPoint(res.latitude,res.longitude,pointType);
          this.mapData.markers=[{lng:Number(transParam.longitude),lat:Number(transParam.latitude)}]
          this.mapData.center=this.mapData.markers[0]
      }
    },
    //打开地图
    showMap(){
      console.log(this.mapData.markers,'----------------------point')
      if(this.mapData.markers.length>0){
        if(localStorage.getItem('mapType')==1){
          this.$store.commit('setVisibleBaiduMap',true)
        }else{
          this.$store.commit('setVisibleGoogleMap',true)
        }
      }else{
        this.$message.error('您未录入电站位置信息')
      }
    }


  }
}
</script>

<style lang="less">
@color_box_bg:#EFEFEF;
@color_title:#444;
@color_text:#636162;
@color_unit:#636162;
@color_light:#ff8920;
@border_bottom:1px dashed #D1D1D1;
@border_radius:3px;
@color_unit:#8a8a8a;
.overview_site{
  .page-title{
    padding: 10px 0 0 10px;
    color: @color_title;
    font-size: 14px;
    span{
      color: @color_light;
    }
  }
  .prompt{
    color: @color_light;
    font-size: 25px;
    margin: 0 20px;
  }
  .flex-container{
    display:-webkit-flex;
    display: flex;

    .flex-item{
      margin: 10px;
      flex:1;
      background:@color_box_bg;
      border-radius: @border_radius;
      .title{
        padding: 0 10px;
        height: 40px;
        line-height: 40px;
        border-bottom: @border_bottom;
        color: @color_title;
      }

      &.sun-box{
        .sun-wrap{
          max-width:420px;
          margin:0 auto;
          color: @color_text;
          .inner .wrap{
            padding:5px 0px;
            text-align: center;
            >*{
              vertical-align: middle;
            }
            label{
              font-size: 14px;
              color: @color_text;
              padding-right: 5px;
            }
            .value{
              font-size:18px;
              color: @color_light;
            }
            .unit{
              font-size: 12px;
              color: @color_unit;
              margin-left:3px ;
            }
            img{
              padding-right: 5px;
              width: 18px;
            }
          }

          .sun-box-pix{
              position: relative;
              height: 200px;
          }
          .sun-gif{
              position: absolute;
              width: 100%;
              overflow: hidden;
              bottom: 0px;
          }

          .sun-rotate{
              position: absolute;
              top: 0px;
              left: 0px;
              transition: 1s;
          }
          .weather-box{
            padding:0 !important;
            width:34%;
            float:left;
            text-align:center;
          }
          .weather-box .weather-info-data{
            font-size: 16px;
            line-height: 70px;
          }
          .inner.no-data span{
            display: block;
            font-size: 14px;
            margin-top: 40px;
            line-height: 25px;
          }
          .weather-info-temperature{
            font-size: 16px;
          }
          .weather-pic-box{
            width: 70px;
            display: block;
            margin: 0 auto;
          }
          .sun-time-day{
            font-size: 12px;
          }
        }
      }

      &.box-power{
        display: flex;
        flex-direction: column;
        .row{
          flex: 1;
          display: flex;
          flex-direction: row;
          align-items: center;
          border-right: 1px solid#DCDCDC;
          &:last-child{
            border-bottom: 1px solid #DCDCDC;
          }
          .col{
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            border-left: 1px solid#DCDCDC;
            border-top: 1px solid#DCDCDC;
            .wrap{
              display: flex;
              width: 100%;
              justify-content: space-between;
              .img{
                flex: 1;
                margin-left:12%;
              }
            }
            .img{
              width: 40px;
              height: 40px;
              background: url(../../assets/img/overview/icons_power.png) no-repeat;
              &.icon1{
                background-position: 0 0;
              }
              &.icon2{
                background-position: 0 -45px;
              }
              &.icon3{
                background-position: 0 -90px;
              }
              &.icon4{
                background-position: 0 -135px;
              }
              >img{
                height:50px;
              }
            }
            .title{
              color: @color_title;
              border-bottom: @border_bottom;
              padding: 6px;
            }
            .text{
              flex:2;
              text-align: left;
              .value{
                font-size: 20px;
                color: @color_light;  
              }
              .unit{
                font-size: 12px;
                color: @color_unit;
                margin-left:3px ;
              }
            }
            p{
              margin: 0;
              color: @color_text;
              font-size: 14px;
            }
          }
        }

      }
      &.box-power-bar{
        position: relative;
        .title{
          >.el-select {
            margin-left:10px;
          }
        }
        .chartBtnWrap{
          float: right;
          li{
            float: left;
            padding-left: 15px;
            cursor: pointer;
            .iconfont{
              font-size: 20px;
              color: @color_unit;
            }
            &.active{
              .iconfont{
                color:@color_light;
              }
            }
          }
        }
        .right-box-radio{
          position: absolute;
          right: 20px;
          z-index: 3;
        }
        .radio-wrap{
          position: relative;
          display: inline-block;
          margin-left:20px;
          font-size: 12px;
          color: @color_text;
          cursor: pointer;
          div{
            display: inline;
            .radio-box-modal {
              display: inline-block;
              width: 8px;
              height: 8px;
              margin-right: 4px;
              border: 1px solid #696969;
              cursor: pointer;
            }
            &.active .radio-box-modal{
              background: #6DA719;
              border-color: #6DA719;
            }
            input{
              display: none;
            }
          }
          .btn-group{
            display: inline;
            .title-btn{
              font-size: 14px;
            }
            ul.box-time{
              display: none;
              position: absolute;
              z-index: 100;
              min-width: 180px;
              background-color: #d8d8d8;
              box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3) !important;
              text-align: center;
              li{
                padding: 0;
                min-width: 30px;
                line-height: 30px;
                font-size: 13px;
                &.title{
                  width: 100%;
                  background: #636363;
                  color: #fff;
                  border-bottom: 1px solid #fff;
                }
                &:not(.title){
                  flex: 1;
                  flex-grow:0;
                }
                &.grow{
                  flex-grow:1;
                }
                &:not(.title):hover {
                  background: #636363;
                  color: #fff;
                }
              }
            }
            .active+.box-time{
              display: flex;
              flex-wrap:wrap;
              justify-content:flex-start;
              align-items:flex-start;
              align-content:flex-start;
            }
          } 
          &.active{
            .btn-group{
              display: block;
            }
          }
        }
        .wrap-chart{
          position: relative;
        }
        .wrap-pie{
          >div{
            float: left;
            width: 50%;
            &[echart]{
              height: 280px;
            }
            &.info{
              text-align: center;
              color: @color_text;
              font-size: 14px;
              .value{
                color: @color_light;
              }
            }
          }
        }
        .wrap-pie,.wrap-bar{
          position: absolute;
          width: 100%;
          height: max-content;
          top: 0;
          left: 0;
          background: #efefef;
          visibility: hidden;
          &.active{
            visibility:visible;
          }
        }

      }
      &.box-info{
        .list{
          padding: 0 10px;
          display: flex;
          flex-direction: column;
          align-content:space-between;
          height: 100%;
          li{
            display: flex;
            flex:1;
            align-items: center;
            &.title{
              padding: 0;
              height: 40px;
              line-height: 40px;
              flex-grow: 0;
              color: @color_title;
            }
            &:not(:first-child){
              padding: 10px 0;
            }
            .img{
              flex:1;
              text-align: right;
              padding-right: 21px;
            }
            .name{
              flex:2;
              font-size: 16px;
              color:@color_text;
            }
            .value{
              float: right;
              font-size: 18px;
              color:@color_light;
            }
          }
        }
      }
      .el-button--primary {
        color: #6d6d6d;
        background-color: #ffffff;
        border-color: #f4b600;
      }
    }

    .time-group{
      float: right;
      .el-input{
        width: 150px;
      }
      button{
        border:none;
        &:focus {
          outline: none;
        }
        &:not(:disabled):hover{
          cursor: pointer;
          color: @color_light;
        }
        i{
          line-height: 24px;
          font-weight: bold;
          font-size: 14px;
          
        }
      }
    }

  }
}
</style>